package com.cheer.ba.view.activity;

import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;

import com.bigkoo.svprogresshud.SVProgressHUD;
import com.cheer.ba.R;
import com.cheer.ba.cache.preference.Session;
import com.cheer.ba.constant.Constants;
import com.cheer.ba.constant.IntentCode;
import com.cheer.ba.constant.IntentKey;
import com.cheer.ba.event.BaseEvent;
import com.cheer.ba.model.UserInfoModel;
import com.cheer.ba.presenter.impl.LoginPresenter;
import com.cheer.ba.utils.ClearCacheUtil;
import com.cheer.ba.utils.Protect;
import com.cheer.ba.utils.StringUtils;
import com.cheer.ba.view.base.BaseCommAty;
import com.litesuits.common.utils.HexUtil;
import com.litesuits.common.utils.MD5Util;

import org.greenrobot.eventbus.EventBus;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 登录界面
 *
 * @author HQ
 *         created at 2017/3/6 0006 15:48
 */
public class LoginAty extends BaseCommAty {

    //手机号
    @BindView(R.id.id_login_edit_phone)
    EditText mEditPhone;
    //存储手机号
    private String mSavePhone;
    //清除手机号
    @BindView(R.id.id_login_clear_phone)
    ImageView mImgClearPhone;

    //密码
    @BindView(R.id.id_login_edit_pw)
    EditText mEditPw;
    //存储密码
    private String mSavePw = "";
    //清除密码
    @BindView(R.id.id_login_clear_pw)
    ImageView mImgClearPw;

    //记录从哪个界面过来
    private int mPage;

    //记录油卡卡号
    private String mCardNum;


    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            final UserInfoModel model = (UserInfoModel) msg.obj;
            mEditPhone.setText(model.getCustPhone());
            SVProgressHUD.showWithStatus(aty, getString(R.string.login_loading));
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    SVProgressHUDDismiss();
                    updateView(model);
                }
            }, 2000);
        }
    };

    @Override
    public View loadView(LayoutInflater inflater, View childView) {
        return super.loadView(inflater, inflater.inflate(R.layout.aty_login, null));
    }

    @Override
    public void initPresenter() {
        presenter = new LoginPresenter();
    }

    @Override
    public boolean hasDataInPage() {
        return true;
    }

    @Override
    public void initView() {
        mPage = getIntent().getIntExtra(IntentKey.General.KEY_PAGE, Constants.DEFAULTVALUE);
        mCardNum = getIntent().getStringExtra(IntentKey.General.KEY_DATA);
        mEditPhone.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                mSavePhone = s + "";
                if (StringUtils.isEmpty(mSavePhone)) {
                    mImgClearPhone.setVisibility(View.GONE);
                } else {
                    mImgClearPhone.setVisibility(View.VISIBLE);
                }
            }

            @Override
            public void afterTextChanged(Editable s) {
            }
        });
        mEditPw.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                mSavePw = s + "";
                if (StringUtils.isEmpty(mSavePw)) {
                    mImgClearPw.setVisibility(View.GONE);
                } else {
                    mImgClearPw.setVisibility(View.VISIBLE);
                }
            }

            @Override
            public void afterTextChanged(Editable s) {
            }
        });
    }

    @Override
    public void initData() {
        mEditPhone.setText(Session.getUserPhone());
        mEditPw.setText("");
    }

    /**
     * 检查输入的信息是否正确
     *
     * @return
     */
    private String checkLogin() {
        int length = mSavePw.length();
        if (StringUtils.isEmpty(mSavePhone) || StringUtils.isEmpty(mSavePw)) {
            return getString(R.string.phone_pw_null);
        } else if (!StringUtils.isMobile(mSavePhone)) {
            return getString(R.string.phone_error);
        } else if (length < 6 || length > 18) {
            return getString(R.string.pw_length);
        } else if (StringUtils.isNumRic(mSavePw) || StringUtils.isLetterRic(mSavePw)) {
            return getString(R.string.pw_had_num_letter);
        } else {
            return "";
        }
    }

    @Override
    public <T> void updateView(T t) {
        if (null != t) {
            SVProgressHUD.showSuccessWithStatus(aty, getString(R.string.login_success));
            UserInfoModel model = (UserInfoModel) t;
            //清除换缓存
            ClearCacheUtil.clearCache(aty, 1, model.getCustId());

            Session.setUserIsLogin(true);
            Session.setUserId(model.getCustId());
            if (StringUtils.isEmpty(model.getOrgId()) || TextUtils.equals("0", model.getOrgId())) {
                Session.setUserOrgId("");
            } else {
                Session.setUserOrgId(model.getOrgId());
            }
            Session.setBeforeLoginId(model.getCustId());
            Session.setSessionKey(model.getToken());
            Session.setUserPicUrl(Protect.setPic(model.getCustImg()));
            Session.setUserPhone(model.getCustPhone());
            Session.setUserLocalUrl(Protect.setPic(model.getCustQr()));
            Session.setUserName(model.getCustNname());
            Session.setUserNo(model.getCustNo());
            Session.setUser_desc(model.getCustDesc());
            Session.setUser_signatrue(model.getCustSignature());
            if (TextUtils.equals("0", model.getCustSex())) {
                Session.setUser_sex("女");
            } else {
                Session.setUser_sex("男");
            }
            Session.setUser_area(model.getCustLocation());
//            if (Type.HAD_SET_PW == model.getIsPayPassword()) {
//                //设置支付密码
//                Session.setUserSetpaypw(true);
//            } else {
//                Session.setUserSetpaypw(false);
//            }
//            if (Type.OPEN_EASY_PAY == model.getSmallNopass()) {
//                //开启免密支付
//                Session.setIsOpenGesture(true);
//            } else {
//                Session.setIsOpenGesture(false);
//            }
//            if (model.getIsPwdExist() == 1) {
//                //设置了登录密码
//                Session.setUserLoginPw(true);
//            } else {
//                Session.setUserLoginPw(false);
//            }

            //登录成功
            BaseEvent event = new BaseEvent();
            event.type = IntentKey.Login.KEY_LOGIN_SUCCESS;
            EventBus.getDefault().post(event);

            //启动推送
            BaseEvent event1 = new BaseEvent();
            event1.type = IntentKey.Login.KEY_START_JPUSH;
            EventBus.getDefault().post(event1);

            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    setResult(IntentCode.Login.LOGIN_RESULT_CODE);
                    if (mPage == IntentCode.General.BACK_ORDER) {
                        //进入订单界面
                        showActivity(aty, MyOilCardAty.class);
                    } else if (mPage == IntentCode.General.BACK_ADD_CARD) {
                        //进入添加油卡界面
                        Intent intent = new Intent(aty, AddOilCardAty.class);
                        if (!StringUtils.isEmpty(mCardNum)) {
                            intent.putExtra(IntentKey.General.KEY_DATA, mCardNum);
                        }
                        showActivity(aty, intent);
                    }
                    SVProgressHUDDismiss();
                    finish();
                }
            }, 1000);
        }
    }

    @OnClick({R.id.id_login_clear_phone, R.id.id_login_clear_pw, R.id.id_login_btn, R.id.id_login_register_btn, R.id.id_login_pw_btn, R.id.layout_login_weixin})
    public void onClick(View mView) {
        switch (mView.getId()) {
            //清除手机号
            case R.id.id_login_clear_phone:
                mEditPhone.setText("");
                mEditPw.setText("");
                break;
            //清除密码
            case R.id.id_login_clear_pw:
                mEditPw.setText("");
                break;
            //登录按钮
            case R.id.id_login_btn:
                String msg = checkLogin();
                if (StringUtils.isEmpty(msg)) {
                    ((LoginPresenter) presenter).login(mSavePhone, HexUtil.encodeHexStr(MD5Util.md5(mSavePw)));
                } else {
                    SVProgressHUD.showInfoWithStatus(aty, msg);
                }
                break;
            //注册
            case R.id.id_login_register_btn:
                Intent register = new Intent(aty, RegisterAty.class);
                register.putExtra(IntentKey.General.KEY_DES, mSavePhone);
                startActivityForResult(register, IntentCode.Register.REGISTER_REQUEST_CODE);
                break;
            //忘记登录密码
            case R.id.id_login_pw_btn:
                Intent forgetPw = new Intent(aty, ForgotPwAty.class);
                forgetPw.putExtra(IntentKey.General.KEY_DES, mSavePhone);
                startActivityForResult(forgetPw, IntentCode.Forget.FORGET_REQUEST_CODE);
                break;
            //微信登录
            case R.id.layout_login_weixin:
                break;
        }
    }

    /**
     * //注册成功(包括从忘记密码中进入或者直接手机号注册)
     *
     * @author HQ
     * created at 2017/3/8 0008 14:47
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == IntentCode.Register.REGISTER_REQUEST_CODE) {
            if (resultCode == IntentCode.Register.REGISTER_RESULT_CODE) {
                if (null != data) {
                    UserInfoModel model = (UserInfoModel) data.getSerializableExtra(IntentKey.General.KEY_MODEL);
                    if (null != model) {
                        Message msg = new Message();
                        msg.obj = model;
                        mHandler.sendMessage(msg);
                    }
                }
            }
        } else if (requestCode == IntentCode.Forget.FORGET_REQUEST_CODE) {
            if (resultCode == IntentCode.Forget.FORGET_RESULT_CODE) {
                if (null != data) {
                    String phone = data.getStringExtra(IntentKey.General.KEY_DES);
                    mEditPhone.setText(phone);
                }
            }
        }
    }
}
